<?php

namespace app\admin\controller\business;

// 引入基类控制器
use app\common\controller\Backend;

class Highsea extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    protected $ReceiveModel = null;

    protected $AdminModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = model('Business.Business');
        $this->AdminModel = model('Admin');
        $this->ReceiveModel = model('Business.Receive');
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            // 过滤请求参数中的html标签和取消两边你空白
            $this->request->filter(['strip_tags', 'trim']);
            // 获取查询参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where('adminid', 'NULL') // 查询没有adminid的
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['source'])
                ->where($where)
                ->where('adminid', 'NULL')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // var_dump($this->model->getLastSql());
            // exit;

            $result = [
                'rows' => $list,
                'total' => $total
            ];

            return json($result);
        }

        return $this->view->fetch();
    }

    // 分配
    public function recovery($ids = null)
    {
        // 分隔id
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->all($ids);

        if (empty($row)) {
            $this->error(__('No Results were found'));
            exit;
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $businessList = []; // 客户信息
            $receiveList = []; // 领取信息

            // 组装数据
            foreach ($row as $v) {
                $businessList[] = [
                    'id' => $v['id'],
                    'adminid' => $params['adminid'],
                ];

                $receiveList[] = [
                    'applyid' => $params['adminid'],
                    'status' => 'allot', // 设置类型为分配
                    'busid' => $v['id']
                ];
            }

            // 开始事务
            $this->model->startTrans();
            $this->AdminModel->startTrans();

            // 更新客户表
            $subResult = $this->model->isUpdate(true)->saveAll($businessList);

            if (!$subResult) {
                $this->error($this->model->getError());
            }

            // 插入领取表
            $receiveResult = $this->ReceiveModel->saveAll($receiveList);

            if (!$receiveResult) {
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if ($subResult && $receiveResult) {
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('分配成功');
                exit;
            } else {
                $this->ReceiveModel->rollback();
                $this->model->rollback();
                $this->error('分配失败');
                exit;
            }
        }

        $adminData = $this->AdminModel->column('id,username');

        $this->assign([
            'row' => $row,
            'AdminData' => $adminData
        ]);

        return $this->view->fetch();
    }

    // 领取
    public function apply($ids = null)
    {
        // 分隔id
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->all($ids);

        if (empty($row)) {
            $this->error(__('No Results were found'));
            exit;
        }

        if ($this->request->isPost()) {
            $businessList = []; // 客户数据
            $receiveList = []; // 领取数据

            // 组装数据
            foreach ($row as $v) {
                $businessList[] = [
                    'id' => $v['id'],
                    'adminid' => $this->auth->id,
                ];

                $receiveList[] = [
                    'applyid' => $this->auth->id,
                    'status' => 'apply', // 设置类型为申请
                    'busid' => $v['id']
                ];
            }

            // 开始事务
            $this->model->startTrans();
            $this->AdminModel->startTrans();

            // 更新客户表
            $subResult = $this->model->isUpdate(true)->saveAll($businessList);

            if (!$subResult) {
                $this->error($this->model->getError());
            }

            // 插入领取表
            $receiveResult = $this->ReceiveModel->saveAll($receiveList);

            if (!$receiveResult) {
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if ($subResult && $receiveResult) {
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('领请成功');
                exit;
            } else {
                $this->ReceiveModel->rollback();
                $this->model->rollback();
                $this->error('领请失败');
                exit;
            }
        }
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->model->all($ids);

        if (empty($row)) {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids); // 软删除

        if (!$result) {
            $this->error($this->model->getError());
            exit;
        }

        $this->success();
        exit;
    }
}
